﻿using Nectar.DAL.Common;
using P2PWeb.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace P2PWeb.Common
{
    public static class DueDateEx
    {
        public static int MonthDifference(this DateTime dueDate)
        {
            return Math.Abs((dueDate.Month - DateTime.Now.Month) + 12 * (dueDate.Year - DateTime.Now.Year));
        }
    }


    public class Order
    {
        /// <summary>
        /// 主键
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 状态
        /// </summary>
        public int Status { get; set; }

        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 借款人
        /// </summary>
        public string LoanPerson { get; set; }

        /// <summary>
        /// 是否热标
        /// </summary>
        public bool IsJvb { get; set; }

        /// <summary>
        /// 完成率
        /// </summary>
        public double FinishRate { get; set; }

        /// <summary>
        /// 剩余时间
        /// </summary>
        public TimeSpan DueDate { get; set; }

        /// <summary>
        /// 金额
        /// </summary>
        public decimal Money { get; set; }

        /// <summary>
        /// 借款期限
        /// </summary>
        public string TimeSpan { get; set; }

        /// <summary>
        /// 年息
        /// </summary>
        public double AnnualInterest { get; set; }

        /// <summary>
        /// 已投标金额
        /// </summary>
        public int RealAmount { get; set; }

        /// <summary>
        /// 投标数
        /// </summary>
        public int NumberOfbids { get; set; }

        /// <summary>
        /// 抵押类型
        /// </summary>
        public string Mortgage { get; set; }

       

    }

    public class OrderDetail
    {
        /// <summary>
        /// 主键
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 状态
        /// </summary>
        public int Status { get; set; }
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 借款人
        /// </summary>
        public string LoanPerson { get; set; }

        /// <summary>
        /// 是否热标
        /// </summary>
        public bool IsJvb { get; set; }

        /// <summary>
        /// 完成率
        /// </summary>
        public double FinishRate { get; set; }

        /// <summary>
        /// 剩余时间
        /// </summary>
        public TimeSpan DueDate { get; set; }

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartDate { get; set; }


        /// <summary>
        /// 金额
        /// </summary>
        public decimal Money { get; set; }

        /// <summary>
        /// 可投金额
        /// </summary>
        public int SurplusMoney { get; set; }

        /// <summary>
        /// 借款期限
        /// </summary>
        public string TimeSpan { get; set; }

        /// <summary>
        /// 年息
        /// </summary>
        public double AnnualInterest { get; set; }

        /// <summary>
        /// 投标数
        /// </summary>
        public int NumberOfbids { get; set; }

        /// <summary>
        /// 借款详情
        /// </summary>
        public string Info { get; set; }

        /// <summary>
        /// 交易类型
        /// </summary>
        public string CalcType { get; set; }

        /// <summary>
        /// 抵押类型
        /// </summary>
        public string Mortgage { get; set; }



        [DisplayName("投标金额")]
        [Required(ErrorMessage="请输入投标金额")]
        [RegularExpression("^[0-9]*$", ErrorMessage = "投标金额必须为数字不能为零并且是100的倍数，")]
        [MoneyRange(100)]
        /// <summary>
        /// 投标金额(扩充 用于出借页面)
        /// </summary>
        public decimal? LendMoney { get; set; }

        public Account account { get; set; }

        public List<Flight> flight { get; set; }
    }


    public class Page
    {
        public int CurrentPageIndex { get; set; }
        public int TotialPaqgerCount { get; set; }
        public int ItemsCount { get; set; }
        public int TotialItemsCount { get; set; }
    }

    public class User
    {
        public string Account { get; set; }

        public string UserName { get; set; }

        public string UserPhone { get; set; }

    }



    public class DefaultJson
    {
        public List<Order> Orders { get; set; }

        public List<Order> FinishOrders { get; set; }

        public Pager<Campaign> Page { get; set; }

        private static Order CreateOrder(int id, string title, string loadPerson, bool isJvb, double finishRate, TimeSpan dubDate, decimal moeny, string timespan, double annualInterest
    , int realamount, int numberOfbids, int status, string mortgage)
        {
            return new Order()
            {
                Id = id,
                Title = title,
                LoanPerson = loadPerson,
                IsJvb = isJvb,
                FinishRate = finishRate,
                DueDate = dubDate,
                Money = moeny,
                TimeSpan = timespan,
                AnnualInterest = annualInterest,
                NumberOfbids = numberOfbids,
                RealAmount = realamount,
                Status = status,
                Mortgage = mortgage
            };
        }


        public static DefaultJson GetDemo(int pageIndex = 1)
        {
            DefaultJson dj = new DefaultJson()
            {
                Orders = new List<Order>(),
                FinishOrders = new List<Order>(),
            };

            using (var context = new Repository<P2PModelContainer>())
            {


                Pager<Campaign> pager = new Pager<Campaign>();
                pager.CurrentPageIndex = pageIndex;
                QueryParameter isDelParameter = new QueryParameter("isDel", false);
                QueryParameter IsJvb = new QueryParameter("IsJvb", true);
                QueryParameter[] pageParameters = pager.GetQueryParameters();
                pager.TotialItemsCount = context.GetListOf<Campaign>("o.IsJvb =@IsJvb and o.Status in {3,4} and o.IsDel=@isDel order by o.CreationTime desc", new[] { isDelParameter, IsJvb }).Take(3).ToList().Count;
                //前台显示3个推荐订单
                pager.Items = context.GetListOf<Campaign>("o.IsJvb =@IsJvb and  o.Status  in {3,4} and o.IsDel=@isDel order by o.CreationTime desc", pageParameters.Union(new[] { isDelParameter, IsJvb }).ToArray()).Take(3).ToList();
                foreach (var item in pager.Items)
                {

                    dj.Orders.Add(CreateOrder(item.ID, item.Name, item.Account.Name, false, (Convert.ToDouble(item.RealAmount) / Convert.ToDouble(item.Amount)), (TimeSpan)(item.EndDate - item.StartDate), item.Amount, item.StartDate.ToString("yyyy-MM-dd") + "至" + item.EndDate.ToString("yyyy-MM-dd"), item.InterestRate, item.RealAmount, item.Flight.Count(), item.Status, EnumHelper.GetDisplayName((MortgageAttachment)item.Mortgage)));

                    if (item.Status == 4)
                    {
                        dj.FinishOrders.Add(CreateOrder(item.ID, item.Name, item.Account.Name, false, 1, (TimeSpan)(item.EndDate - item.StartDate), item.Amount, item.StartDate.ToString("yyyy-MM-dd") + "至" + item.EndDate.ToString("yyyy-MM-dd"), item.InterestRate, item.RealAmount, item.Flight.Count(), item.Status, EnumHelper.GetDisplayName((MortgageAttachment)item.Mortgage)));
                    }

                }

                dj.Page = pager;
                

                

            }

            return dj;
        }

        public static DefaultJson GetDemo1(int pageIndex = 1)
        {
            DefaultJson dj = new DefaultJson()
            {
                Orders = new List<Order>(),
                FinishOrders = new List<Order>(),
            };

            using (var context = new Repository<P2PModelContainer>())
            {
                Pager<Campaign> pager = new Pager<Campaign>();
                pager.CurrentPageIndex = pageIndex;
                QueryParameter isDelParameter = new QueryParameter("isDel", false);
                QueryParameter[] pageParameters = pager.GetQueryParameters();
                pager.TotialItemsCount = context.GetListOf<Campaign>("o.Status  = 4 and o.IsDel=@isDel order by o.CreationTime desc", new[] { isDelParameter }).Count;
                pager.Items = context.GetListOf<Campaign>("o.Status  = 4 and o.IsDel=@isDel order by o.CreationTime desc", pageParameters.Union(new[] { isDelParameter }).ToArray());


                //var query = context.GetListOf<Campaign>("o.Status  = 4  and o.Isdel = false order by o.CreationTime desc", null).Take(100);,
                foreach (var item in pager.Items)
                {
                    dj.Orders.Add(CreateOrder(item.ID, item.Name, item.Account.Name, false, (Convert.ToDouble(item.RealAmount) / Convert.ToDouble(item.Amount)), (TimeSpan)(item.DueDate - DateTime.Now), item.Amount, item.StartDate.ToString("yyyy-MM-dd") + "至" + item.EndDate.ToString("yyyy-MM-dd") + ((item.EndDate.Year - item.StartDate.Year) * 12), item.InterestRate, item.RealAmount, item.Flight.Count(), item.Status, EnumHelper.GetDisplayName((MortgageAttachment)item.Mortgage)));
                }
                dj.Page = pager;

            }

            return dj;
        }

        public static DefaultJson GetLendrsSearch(Hashtable ht = null ,int pageIndex = 1)
        {
            DefaultJson dj = new DefaultJson()
            {
                Orders = new List<Order>(),
                FinishOrders = new List<Order>(),
            };

            using (var context = new Repository<P2PModelContainer>())
            {
                string sql = "o.Status in {3,4} and o.IsDel=@isDel";
                Pager<Campaign> pager = new Pager<Campaign>();
                pager.CurrentPageIndex = pageIndex;
                QueryParameter isDelParameter = new QueryParameter("isDel", false);
                QueryParameter[] pageParameters = pager.GetQueryParameters();
                if (ht != null)
                {
                    if (ht["iapproveNo"].ToString() != "-1")
                    {
                        sql += " and month( o.EndDate - o.StartDate) <=  " + ht["iapproveNo"].ToString();
                    }
                    if (ht["currRate"].ToString() != "-1")
                    {
                        sql += " and o.InterestRate >=  " + ht["currRate"].ToString();
                    }
                    if (ht["iapproveAmt"].ToString() != "-1")
                    {
                        sql += " and o.Amount <=  " + ht["iapproveAmt"].ToString();
                    }
                }
                sql += " order by o.CreationTime desc";

                pager.TotialItemsCount = context.GetListOf<Campaign>("o.Status in {3,4} and o.IsDel=@isDel order by o.CreationTime desc", new[] { isDelParameter }).Count;
                pager.Items = context.GetListOf<Campaign>(sql, pageParameters.Union(new[] { isDelParameter }).ToArray());


                foreach (var item in pager.Items)
                {
                    dj.Orders.Add(CreateOrder(item.ID, item.Name, item.Account.Name, false, (Convert.ToDouble(item.RealAmount) / Convert.ToDouble(item.Amount)), (TimeSpan)(item.DueDate - DateTime.Now), item.Amount, item.StartDate.ToString("yyyy-MM-dd") + "至" + item.EndDate.ToString("yyyy-MM-dd") + ((item.EndDate.Year - item.StartDate.Year) * 12), item.InterestRate, item.RealAmount, item.Flight.Count(), item.Status, EnumHelper.GetDisplayName((MortgageAttachment)item.Mortgage)));
                }
                dj.Page = pager;

            }

            return dj;
        }

    }
}